package storage

import (
	"duoke/utils/gconv"
	"errors"
	"mime/multipart"
	"path/filepath"
	"strings"
)

func Valid(headers *multipart.FileHeader, setting *StructConfig) error {
	if setting.LimitSize != 0 && headers.Size > 1024*1024*setting.LimitSize {
		return errors.New("文件大小应在" + gconv.String(setting.LimitSize) + "M以内")
	}
	// 文件后缀验证,jpg,png
	suffix := filepath.Ext(headers.Filename)
	if setting.LimitSuffix != "" && !strings.Contains(setting.LimitSuffix, strings.ToLower(suffix)[1:]) {
		return errors.New("只允许上传" + setting.LimitSuffix + "类型文件")
	}
	// 文件类型验证，image/png,image/jpeg
	if setting.LimitType != "" && !strings.Contains(setting.LimitType, headers.Header.Get("Content-Type")) {
		return errors.New("只允许上传" + setting.LimitType + "类型文件")
	}
	return nil
}
